package vmcs.boundary;

import java.awt.Button;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import vmcs.controller.CustomerController;
import vmcs.controller.MaintenanceController;
import vmcs.controller.StoreController;
import vmcs.entity.CashStoreItem;
import vmcs.entity.DrinksStoreItem;
import vmcs.entity.StoreItem;

public class CustomerPanelNew extends Dialog {

    public enum CompType {

        CompCoin, CompDrink, CompNIS, CompCoinInvalidLb
    };
    
    private static final long serialVersionUID = 1L;
    private static final String TITLE = "Customer Panel";
    //Variables for top panel
    private int TtlCoinOpt = 0;
    private JPanel panel_coin;
    private JButton[] btnCoins;
    private Label coininvalidlb;
    private LabelledDisplay lblTotalMoneyInserted;
    //Variable for center panel
    private JPanel panel_center;
    private int TtlDrinkOpt = 0;
    private JButton[] btnDrinks;
    private JButton[] btnNISDrinks;
    private JLabel[] labelDrinkPrices;
    private boolean m_coinPanelFlag;
    //Variable for bottom panel
    private JButton btnNoChangeAvailable;
    private JButton btnTerButton;
    private LabelledDisplay lblCollectCoins;
    private LabelledDisplay lblNoCan;
    private Label selectedDrinklb;
    private CoinDisplayCustomer cDisplay; // need to be access from other class.
    private DrinkDisplayCustomer dDisplay;  // need to be access from other class.
    private ButtonItem totalCash;
    private Button transferCash;
    private CustomerController mctrl;

    public CustomerPanelNew(Frame fr, CustomerController mc, MaintenanceController maintController) {
        super(fr, TITLE, false);
        mctrl = mc;
        createTopPanel();
        createCenterPanel();
        createBottomPanel();

        pack();
        setLocation(200, 100);

        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.err.println("Maintenance Dialog Box closing");
                if (mctrl.closeDown()) {
                    closeDown();
                }
            }
        });
    }

    private void createTopPanel() {
        JPanel panel_top = new JPanel();
        panel_top.setLayout(new GridBagLayout());
        GridBagConstraints ctop = new GridBagConstraints();
        //natural height, maximum width

        Label titlelb = new Label("VIMTO Soft Drink Dispenser");
        titlelb.setFont(new Font("Helvetica", Font.BOLD, 24));
        ctop.weightx = 0.5;
        ctop.fill = GridBagConstraints.HORIZONTAL;
        ctop.gridx = 0;
        ctop.gridy = 0;
        panel_top.add(titlelb, ctop);

        Label coinlb = new Label("Enter Coins Here:", Label.LEFT);
        coinlb.setFont(new Font("Helvetica", Font.BOLD, 12));
        //coinlb.set
        ctop.weightx = 0.5;
        ctop.fill = GridBagConstraints.HORIZONTAL;
        ctop.gridx = 0;
        ctop.gridy = 1;
        ctop.ipady = 0;
        panel_top.add(coinlb, ctop);

        panel_coin = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel_coin.setLayout(new GridLayout(1, 0));


        StoreItem[] coinItems = mctrl.getStoreItems(StoreController.CASH);
        this.TtlCoinOpt = coinItems.length + 1;
        btnCoins = new JButton[TtlCoinOpt];


        //Set all the coins option  
        int i = 0;
        for (StoreItem item : coinItems) {
            final int idx = i;
            final CashStoreItem coinItem = (CashStoreItem) item;
            final String coinLabel = item.getContent().getName();
            JButton btn = new JButton(coinLabel);
            int qty = item.getQuantity();
            
            btn.setBackground(Color.WHITE);
            btn.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    //System.out.println("You clicked the button " + coinLabel);
                    mctrl.onInsertCoinEvent(coinItem, coinLabel, idx);
                }
            });
            btn.setEnabled(qty>0);
            btnCoins[i] = btn;
            panel_coin.add(btnCoins[i]);
            ++i;
        }


        //Set invalid option
        final String coinLabel = "Invalid";
        JButton btn = new JButton(coinLabel);
        btn.setBackground(Color.WHITE);
        final int idx = i;
        btn.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                //System.out.println("You clicked the button " + coinLabel);
                mctrl.onInsertCoinEvent(null, coinLabel, idx);
            }
        });
        btnCoins[i] = btn;
        panel_coin.add(btnCoins[i]);

        ctop.fill = GridBagConstraints.HORIZONTAL;
        ctop.gridx = 0;
        ctop.gridy = 2;
        ctop.ipady = 10;
        panel_top.add(panel_coin, ctop);



        coininvalidlb = new Label("Invalid", Label.CENTER);
        coininvalidlb.setFont(new Font("Helvetica", Font.BOLD, 12));
        coininvalidlb.setBackground(Color.RED);
        coininvalidlb.setForeground(Color.WHITE);

        ctop.weightx = 0.5;
        ctop.fill = GridBagConstraints.HORIZONTAL;
        ctop.gridwidth = 40;
        ctop.insets = new Insets(10, 150, 0, 150);  //top padding    
        ctop.weightx = 20;
        ctop.gridx = 0;
        ctop.gridy = 3;
        ctop.ipady = 10;
        panel_top.add(coininvalidlb, ctop);


        lblTotalMoneyInserted = new LabelledDisplay("Total Money Inserted", LabelledDisplay.DEFAULT, LabelledDisplay.FLOW);
        lblTotalMoneyInserted.setTextBackground(Color.BLACK);
        lblTotalMoneyInserted.setTextForeground(Color.YELLOW);
        lblTotalMoneyInserted.setEditable(false);
        lblTotalMoneyInserted.setValue(0);
        ctop.weightx = 0.5;
        ctop.fill = GridBagConstraints.HORIZONTAL;
        ctop.gridwidth = 40;
        ctop.insets = new Insets(10, 10, 0, 10);  //top padding    
        ctop.weightx = 20;
        ctop.gridx = 0;
        ctop.gridy = 4;
        ctop.ipady = 10;
        panel_top.add(lblTotalMoneyInserted, ctop);
        this.add("North", panel_top);
        setCoinPanelEnable(false);

    }

    private void createCenterPanel() {

        panel_center = new JPanel(new FlowLayout(FlowLayout.LEFT));
        panel_center.setLayout(new GridLayout(0, 1));

        JPanel drinkPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        GridLayout drinkLayout = new GridLayout(5, 3);
        drinkPanel.setLayout(drinkLayout);

        StoreItem[] drinkItems = mctrl.getStoreItems(StoreController.DRINK);
        this.TtlDrinkOpt = drinkItems.length;
        btnDrinks = new JButton[TtlDrinkOpt];
        btnNISDrinks = new JButton[TtlDrinkOpt];
        labelDrinkPrices = new JLabel[TtlDrinkOpt];

        int i = 0;
        for (StoreItem item : drinkItems) {
            final int idx = i;
            final DrinksStoreItem drinkItem = (DrinksStoreItem) item;
            //Set drink button
            final String label = drinkItem.getContent().getName();
            JButton btn1 = new JButton(label);
            
            int qty = item.getQuantity();
            
            btn1.setBackground(Color.WHITE);
            btn1.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    //System.out.println("You clicked the button " + label );
                    setDrinkSelectedLabel(label);
                    mctrl.onSelectDrinkEvent(drinkItem, label, idx);
                }
            });
            btn1.setEnabled(qty>0);
            btnDrinks[i] = btn1;
            drinkPanel.add(btnDrinks[i]);

            //Set drink price label
            JPanel pane_lblc = new JPanel();
            int price = drinkItem.getPrice();
            JLabel lblc = new JLabel(String.valueOf(price));
            lblc.setForeground(Color.YELLOW);
            labelDrinkPrices[i] = lblc;
            pane_lblc.setBackground(Color.DARK_GRAY);
            pane_lblc.add(lblc);
            pane_lblc.setBorder(BorderFactory.createLineBorder(Color.black));
            drinkPanel.add(pane_lblc);

            //Set stock status
            JButton btn2 = new JButton("Not in Stock");
            btn2.setForeground(Color.RED);
            btn2.setBackground(Color.GRAY);
            btn2.setEnabled(qty==0);
            btnNISDrinks[i] = btn2;
            drinkPanel.add(btnNISDrinks[i]);
            ++i;
        }

        panel_center.add(drinkPanel);
        this.add("Center", panel_center);
    }

    private void createBottomPanel() {
        JPanel panel_bottom = new JPanel(/*new FlowLayout(FlowLayout.LEFT)*/);
        panel_bottom.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        //natural height, maximum width

        selectedDrinklb = new Label("Drink selected: NA", Label.CENTER);
        selectedDrinklb.setFont(new Font("Helvetica", Font.BOLD, 15));
        //coinlb.set
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(10, 0, 0, 0);  //top padding
        c.gridx = 0;
        c.gridy = 0;
        panel_bottom.add(selectedDrinklb, c);

        btnNoChangeAvailable = new JButton("No change available");
        c.weightx = 0.5;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = 40;
        c.insets = new Insets(20, 50, 0, 50);  //top padding    
        c.weightx = 20;
        c.gridx = 0;
        c.gridy = 1;
        c.ipady = 10;
        panel_bottom.add(btnNoChangeAvailable, c);

        btnTerButton = new JButton("Terminate and Return Cash");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(20, 50, 0, 50);  //top padding    
        c.gridx = 0;
        c.gridy = 2;
        btnTerButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                //System.out.println("You clicked the button " + coinLabel);
                mctrl.onTerminateSelectionEvent();
            }
        });
        panel_bottom.add(btnTerButton, c);

        lblCollectCoins = new LabelledDisplay("Collect Coins", LabelledDisplay.DEFAULT, LabelledDisplay.FLOW);
        lblCollectCoins.setTextBackground(Color.BLACK);
        lblCollectCoins.setTextForeground(Color.YELLOW);
        lblCollectCoins.setValue(" 0 c");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 50, 0, 50);  //top padding    
        c.gridx = 0;
        c.gridy = 3;
        panel_bottom.add(lblCollectCoins, c);

        lblNoCan = new LabelledDisplay("Collect Can Here", LabelledDisplay.DEFAULT, LabelledDisplay.FLOW);
        lblNoCan.setTextBackground(Color.BLACK);
        lblNoCan.setTextForeground(Color.YELLOW);
        lblNoCan.setValue("        No Can        ");
        //lblNoCan.setPreferredSize(new Dimension(20, 100));
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(0, 30, 0, 30);  //top padding    
        c.gridx = 0;
        c.gridy = 4;
        panel_bottom.add(lblNoCan, c);

        this.add("South", panel_bottom);
    }

    public void display() {
        System.out.println("MaintenancePanel: before display");
        this.setVisible(true);
        System.out.println("MaintenancePanel: after display");

    }

    public void closeDown() {
        dispose();
    }

    public CoinDisplayCustomer getCoinDisplay() {
        return cDisplay;
    }

    public DrinkDisplayCustomer getDrinksDisplay() {
        return dDisplay;
    }

    public void setDrinkSelectedLabel(String s) {
        selectedDrinklb.setText("Drink selected: " + s);
    }

    public void displayTotalCoinInserted(int val) {
        lblTotalMoneyInserted.setValue(val);
    }

    public void dispenseDrink(String drinkbrand) {
        lblNoCan.setValue(drinkbrand);
    }

    public void returnChange(int change) {
        lblCollectCoins.setValue(String.valueOf(change) + "C");
    }

    public void updateDrinkPrice(String comp, StoreItem storeItem) { 
        if(storeItem != null){
            DrinksStoreItem drinkItem = (DrinksStoreItem) storeItem;
            int price = drinkItem.getPrice();
            for (int i = 0; i < TtlDrinkOpt; ++i) {
                String s = btnDrinks[i].getText();
                if (btnDrinks[i].getText().equals(comp)) {
                     labelDrinkPrices[i].setText(String.valueOf(price));
                     return;
                }
            }
        }
    }
    
    public void setActive(CompType type, String comp, boolean st) {
        int i;
        switch (type) {
            case CompCoin:
                for (i = 0; i < TtlCoinOpt; ++i) {
                    if (btnCoins[i].getText().equals(comp) ) {
                        btnCoins[i].setEnabled(st);
                    }
                }
                break;
            case CompDrink:
                for (i = 0; i < TtlDrinkOpt; ++i) {
                    if (btnDrinks[i].getText().equals(comp)) {
                        btnDrinks[i].setEnabled(st);
                    }
                }
                break;
            case CompNIS:
                for (i = 0; i < TtlDrinkOpt; ++i) {
                    if (btnDrinks[i].getText().equals(comp)) {
                        btnNISDrinks[i].setEnabled(st);
                    }
                }
                break;
            case CompCoinInvalidLb:
                coininvalidlb.setVisible(st);
        }
    }

    public void updateDrinkPrice(String strDrink, String price) {
        for (int i = 0; i < TtlDrinkOpt; ++i) {
            if (btnDrinks[i].getText().equals(strDrink)) {
                labelDrinkPrices[i].setText(price);
            }
        }
    }

    public boolean getCoinPanelEnable() {
        return m_coinPanelFlag;
    }

    public void setChangeValue(String val) {
        btnNoChangeAvailable.setText(val);
    }

    public void setDrinkPanelEnable(boolean st) {
        StoreItem[] coinItems = mctrl.getStoreItems(StoreController.DRINK);
        for (int i = 0; i < TtlDrinkOpt; ++i) {
            if(coinItems[i].getQuantity() > 0){
                btnDrinks[i].setEnabled(st);
            }
            else {
                btnDrinks[i].setEnabled(false);
            }
                
        }
    }
    
    public void setCoinPanelEnable(boolean st) {
        StoreItem[] coinItems = mctrl.getStoreItems(StoreController.CASH);
        for (int i = 0; i < TtlCoinOpt; ++i) {
            if( (i<coinItems.length) && (coinItems[i].getQuantity() > 0) )
                btnCoins[i].setEnabled(st);
            else {
                if( TtlCoinOpt-1 == i)
                    btnCoins[i].setEnabled(st);
                else btnCoins[i].setEnabled(false);
            }
        }
        m_coinPanelFlag = st;
    }
}
